# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo, donggu

import re
import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def generate():
  mea = 'Spot.Quoinex.v2'
  me = 'Spot.Quoinex'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get('https://api.liquid.com/products').json()

  pis = []
  for info in data:
    native_symbol = info['currency_pair_code']
    native_base = info['base_currency']
    native_quote = info['quoted_currency']
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)

    if info["disabled"] == True:
      continue

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=float(info['tick_size']),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  # fill in qty_ticksize from another source
  # https://help.liquid.com/en/articles/3339119-minimum-order-quantity
  # |            BTC           |                0.001                   |
  html = requests.get('https://help.liquid.com/en/articles/3339119-minimum-order-quantity').text
  pairs = re.findall(r'\|\s+([A-Z]+)\s+\|\s+([0-9\.]+)\s+\|', html)  # [('BTC', '0.001'), ..]
  pairs = {k: float(v) for (k, v) in pairs}
  for pi in pis:
    if pi['native_base'] in pairs:
      pi['qty_ticksize'] = pairs[pi['native_base']]
    else:
      pi['qty_ticksize'] = 0  # FIXME before trade

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
